﻿using AntdUI;
using ImportPlcPointPosition.Models.Dto;
using ImportPlcPointPosition.Utils;
using Mapster;
using MiniExcelLibs;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Model.Models.ProductionControl;

namespace ImportPlcPointPosition.Controls
{
    public partial class AlarmDictPage : BaseUserControl
    {
        public AlarmDictPage()
        {
            InitializeComponent();
            InitTable();
            db = SqlSugarHelper.MesDB;
        }
        SqlSugarClient db = null;
        BindingList<CksAlarmDict> Source = new BindingList<CksAlarmDict>();
        public override void ReflushPage()
        {
            
            QueryData();
        }

        private void QueryData()
        {
            Source.Clear();
            Stopwatch stopwatch = Stopwatch.StartNew();
            var lst = db.Queryable<CksAlarmDict>()
                   .OrderBy(a => a.Id)
                   .ToList();
            stopwatch.Stop();
            Debug.WriteLine($"查询耗时{stopwatch.ElapsedMilliseconds}ms");
            Source = new BindingList<CksAlarmDict>(lst);
            tbDict.Binding(Source);
        }

        private void InitTable()
        {
            tbDict.EditMode = TEditMode.None;
            tbDict.Columns = new ColumnCollection();
            tbDict.Columns.Add(new Column("BitId", "位编号"));
            tbDict.Columns.Add(new Column("SignalAddress", "地址"));
            tbDict.Columns.Add(new Column("DeviceName", "设备名称"));
            tbDict.Columns.Add(new Column("AlarmCode", "报警代码")); // 采用下拉选择
            tbDict.Columns.Add(new Column("FaultCase", "故障原因"));
            tbDict.Columns.Add(new Column("Solution", "解决方法"));

            tbDict.Bordered = true;
            tbDict.EnableHeaderResizing = true;
            tbDict.EmptyHeader = true;
            tbDict.Gap = 6;
            tbDict.VisibleHeader = true;

           
            tbDict.CellBeginEditInputStyle += (s, e) =>
            {
                e.Input.SelectAll();
            };
            //table1.CellClick += Table1_CellClick;
           
        }


        private void btnImportExcel_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(报警字典文件)|*.xlsx";
            var dialog = ofd.ShowDialog();
            if (dialog == DialogResult.OK)
            {
                var fname = ofd.FileName;
                var datas = MiniExcel.Query<ImportAlarmDictDto>(fname).Adapt<List<CksAlarmDict>>();
                foreach (var item in datas)
                {
                    //var fixindex = item.Id - 1;
                    //var DIndex = fixindex / 16;
                    //var bitIndex = fixindex % 16;

                    

                    item.AlarmCode = item.Id.ToString();
                    // 解析出位编号
                    var result = ParseDbString(item.SignalAddress);
                    item.BitId = result.Value.x*8 + result.Value.y +1;
                    item.SignalAddress = $"DBX{result.Value.x}.{result.Value.y}";

                }
                db.DbMaintenance.TruncateTable<CksAlarmDict>();
                db.Insertable(datas).ExecuteCommand();
                QueryData();
                MessageInfo("OK");
            }
        }

        private void btnLoadData_Click(object sender, EventArgs e)
        {
            QueryData();
        }

        public static (int dbNumber, int x, int y)? ParseDbString(string input)
        {
            try
            {
                // 去除开头的%符号
                string temp = input.TrimStart('%');

                // 检查是否以DB开头
                if (!temp.StartsWith("DB"))
                {
                    return null;
                }

                // 提取DB后面的部分
                temp = temp.Substring(2);

                // 分割为DB号和后续部分
                string[] parts = temp.Split(new[] { ".DBX" }, StringSplitOptions.None);
                if (parts.Length != 2)
                {
                    return null;
                }

                // 解析DB号
                if (!int.TryParse(parts[0], out int dbNumber))
                {
                    return null;
                }

                // 分割坐标部分
                string[] coordinates = parts[1].Split('.');
                if (coordinates.Length != 2)
                {
                    return null;
                }

                // 解析X和Y坐标
                if (!int.TryParse(coordinates[0], out int x) ||
                    !int.TryParse(coordinates[1], out int y))
                {
                    return null;
                }

                return (dbNumber, x, y);
            }
            catch
            {
                return null;
            }
        }
    }
}
